import { get } from 'lodash-es'
import { countries } from './codes/zh.json'

const flags = import.meta.glob('./flags/*.webp', { eager: true })
const flagsMap = Object.keys(flags).reduce(
  (acc, key) => {
    const code = key.replace('./flags/', '').replace('.webp', '')
    acc[code] = (flags[key] as Recordable).default
    return acc
  },
  {} as Record<string, any>,
)

export function flagUrl(code?: string): string | undefined {
  if (!code)
    return undefined
  return get(flagsMap, code.toLowerCase())
}

// 获取语言数据
export function getCodesOptions(): Array<LabelValue<string>> {
  return (Object.keys(countries) as Array<string>).reduce(
    (acc, code: string) => {
      acc.push({
        label: get(countries, code),
        value: String(code).toLowerCase(),
      })
      return acc
    },
    [] as Array<LabelValue<string>>,
  )
}

export { flags }
